package com.tuniu.agents.impl.widgets.logger;

import com.tuniu.agents.common.i18n.I18nConstants;
import com.tuniu.agents.impl.widgets.constants.RestaurantConstants;
import com.tuniu.agents.message.MessageRender;
import com.tuniu.agents.message.ToolLogger;
import com.tuniu.agents.tools.widgets.tool.RestaurantListTool;
import com.tuniu.agents.util.I18nUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service(RestaurantToolLoggingService.BEAN_NAME)
public class RestaurantToolLoggingService implements ToolLogger {

    public static final String BEAN_NAME = "restaurantToolLoggingService";

    @Autowired
    private MessageRender messageRender;

    @Override
    @SneakyThrows
    public List<String> before(Object request, ToolContext context) {
        if (Objects.isNull(request)) {
            return null;
        }
        String conversationId = (String) context.getContext().get(RestaurantConstants.CONVERSATION_ID);
        if (request instanceof RestaurantListTool.Request poiRequest) {
            if (!StringUtils.hasText(poiRequest.placeName())) return null;

            String markdownResponse = messageRender.renderTemplate(RestaurantConstants.THINKING_TOOL_SEARCH_TEMPLATE_NAME,
                    Map.of(I18nConstants.LANGUAGE_TAG, I18nUtil.getLocaleLanguageTag(conversationId)),
                    new Object[]{poiRequest.placeName()});

            return List.of(markdownResponse);
        }
        return null;
    }

    @Override
    @SneakyThrows
    public List<String> after(Object request, ToolContext context, Object response) {
        if (Objects.isNull(response) || Objects.isNull(request)) {
            return null;
        }
        String conversationId = (String) context.getContext().get(RestaurantConstants.CONVERSATION_ID);
        if (response instanceof RestaurantListTool.ReqRespWrap reqRespWrap) {
            if (CollectionUtils.isEmpty(reqRespWrap.response().data())) {
                return null;
            }
            String markdownResponse = messageRender.renderTemplate(RestaurantConstants.THINKING_TOOL_FOUND_TEMPLATE_NAME,
                    Map.of(I18nConstants.LANGUAGE_TAG, I18nUtil.getLocaleLanguageTag(conversationId)),
                    new Object[]{reqRespWrap.response().data().size()});
            return List.of(markdownResponse);
        }
        return null;
    }
}
